getAllTables();
$(document).ready(function() {
	$('#playerLabel').hide();
	$('#betValue').hide();
	$('#btnSave').hide();
	$('#betOption').hide();
	checkLoginAtStart();
	setInterval(function(){updateAll();},1000);
});

function checkLoginForm(){
	var username = $('#username').val();
	var password = $('#password').val();
	$.getJSON('rest/game/login/' + username + '/' + password, function(data) {
		if(data == null){
			alert("login failed");
		} else {
			insertParam("?username="+username+"&password="+password);
		}
	});
}

function insertParam(value){
    document.location.search = value;
}

function checkLoginAtStart(){
	var checkUsername = getParameter('username');
	var checkPassword = getParameter('password');
	if((checkUsername == null) && (checkPassword == null)){
		$('#login').show();
		$('#wrapper').hide();
	} else {
		$('#login').hide();
		$('#wrapper').show();
	}
}

//*** Menu ***//
$('#tableList a').live('click', function() {
	var id = $(this).data('identity');
	if (id == -1) {
		leaveTable(id);
		getAllTables();
	} else {
		joinTable($(this).data('identity'));
	}
});

$('#playerList a').live('click', function() {
	var id = $(this).data('identity');
	if (id == -1) {
		findTableById($(this).data('tableid'));
	} else {
		showDetailedPlayerInfo($(this).data('tableid'), $(this).data('name'));
	}
});

//*** Menu -> End ***//

function addBet(){
	var field = $('#betOption').val();
	var value = $('#betValue').val();
	$('#betValue').value = "0";
	$.ajax({
		type: 'PUT',
		contentType: 'application/json',
		url: "rest/game/bet/"+field+"/"+value+"?username="+getParameter('username')+"&password="+getParameter('password')
	});
	
}

function registerPlayer(){
	var username = $('#username').val();
	var password = $('#password').val();
	$.ajax({
		type: 'PUT',
		contentType: 'application/json',
		url: "rest/game/player/"+username+"/"+password
	});
}

function joinTable(i){
	$.ajax({
		type: 'PUT',
		contentType: 'application/json',
		url: 'rest/game/join/' + i + '/?username=' +getParameter('username')+"&password="+getParameter('password'),
		success: function(data){
		drawTable(data);
	}
	});
}

function drawTable(data){
	var table = data;
	$('#tableLabel').text("Table:");
	$('#tableList li').remove();
	$('#tableList').attr("data-role", "listview");
	$('#tableList').append(
			'<li><a id="currentTable" href="#" data-identity="' + table["id"] + '">'
					+ table["id"] + '</a></li>');
	$('#tableList').append(
			'<li><a href="#" data-identity="' + -1 + '">' + "Leave Table"
					+ '</a></li>');
	$('#playerLabel').show();
	$('#playerList li').remove();
	var playerObject = table["players"];
	$.each(playerObject, function(id, player) {
		$('#playerList').append(
				'<li><a href="#" data-identity="' + id + '" data-name="'
						+ player.name + '" data-tableid="' + table["id"]
						+ '" >' + player.name + " " + player.stack +  '</a></li>');
	});
	$('#tableList').listview('refresh');
	$('#playerList').listview('refresh');
}

function leaveTable(){
	$.ajax({
		type: 'DELETE',
		contentType: 'application/json',
		url: 'rest/game/leavetable?username=' +getParameter('username')+"&password="+getParameter('password')
	});
}

function getAllTables() {
	$.getJSON('rest/game/', function(data) {
		var tableObject = data.table;
		$('#leftArea').hide();
		$('#tableLabel').text("Tables:");
		$('#tableList li').remove();
		$.each(tableObject, function(id, table) {
			$('#tableList').append(
					'<li><a href="#" data-identity="' + table["id"] + '">'
							+ table["id"] + '</a></li>');

		});
		$('#leftArea').slideDown('slow');
		$('#playerLabel').hide();
		$('#playerList li').remove();
		$('#tableList').listview('refresh');
		$('#playerList').listview('refresh');
	});
}
	
function showDetailedPlayerInfo(tableid, playerName) {
	$.getJSON('rest/game/' + tableid + '/' + playerName, function(data) {
		var player = data;
		$('#playerList li').remove();
		$('#playerList').append(
				'<li><a href="#" data-identity="' + 0 + '">' + player.name
						+ "<br /> " + player.stack + '</a></li>');
		$('#playerList').append(
				'<li><a href="#" data-identity="' + -1 + '" data-name="'
						+ player.name + '" data-tableid="' + tableid + '" >'
						+ "Back" + '</a></li>');
	});
}

function getParameter(paramName) {
	var searchString = window.location.search.substring(1), i, val, params = searchString
			.split("&");
	for (i = 0; i < params.length; i++) {
		val = params[i].split("=");
		if (val[0] == paramName) {
			return unescape(val[1]);
		}
	}
	return null;
}

function isNumberKey(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode;
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return true;
}

function updateAll() {
	var color = "green";

	$.getJSON('rest/game/' + $('#currentTable').text()+"?username=" + getParameter('username')+"&password="+getParameter('password'), function(data) {
		var tableResult = data;
		if($('#currentTable').text() == ""){
			$('#betValue').hide();
			$('#btnSave').hide();
			$('#betOption').hide();
			$('.nameLabel').hide();
		}else{
			$('#betValue').show();
			$('#btnSave').show();
			$('#betOption').show();
			$('.nameLabel').show();
		}
		$('#console').html("");
		$.each(tableResult.fields, function(id, field) {
			$.each(field, function(bid, bet) {	
				if(field.index == tableResult.result){
					color = field.name;
				}
				if(bet["value"]!=null){
					if(parseInt(field["index"]) < 36){
						$('#console').append('<li>Op plek ' + field["index"] + " heeft " + bet["playerName"] + " $" + bet["value"] + " ingezet " + ' </li>');
					}
					else{
						$('#console').append('<li>Op plek ' + field["name"] + " heeft " + bet["playerName"] + " $" + bet["value"] + " ingezet " + ' </li>');
					}
				}
			});
		});
		$('#resultBlock').css("background-color", color); 
		$('.resultText').html(tableResult.result);
		$('.timeText').html("<br />Ronde eindigt over: <br /> ");
		$('.timeLeft').html((30 - tableResult.counter));
		drawTable(tableResult);
	});
};